const fs = require("fs");

function parseWeixinBook(infos) {
  // 书名：大道PHP——LAMP+Zend+开源框架整合开发与实战作者：三扬科技出版社：电子工业出版社出版时间：2009-09ISBN：9787121091711

  function find(name, next) {
    const startIndex = infos.indexOf(name) + name.length;
    const endIndex = next ? infos.indexOf(next) : undefined;
    return infos.substring(startIndex, endIndex);
  }

  const bookName = find("书名：", "作者：");
  const author = find("作者：", "出版社：");
  const publisher = find("出版社：", "出版时间：");
  const releaseTime = find("出版时间：", "ISBN：");
  const isbn = find("ISBN：");
  return {
    bookName,
    author,
    publisher,
    releaseTime,
    isbn,
  };
}

function parseDoubanBook(bookName, input) {
  /**
   * 作者: Josh Lockhart
   * 出版社: 中国电力出版社
   * 译者: 安道
   * 出版年: 2015-9
   * 页数: 219
   * 定价: 39
   * 装帧: 平装
   * 丛书: O'Reilly动物系列（中译本）
   * ISBN: 9787512380936
   */

  const book = {};
  const lines = input.split("\n");
  lines.forEach((line) => {
    if (line.indexOf(":") >= 0) {
      const keyValuePair = line.split(":");
      const key = keyValuePair[0].trim();
      const value = keyValuePair[1].trim();
      book[key] = value;
    }
  });

  function find(name, next) {
    const startIndex = input.indexOf(name) + name.length;
    const endIndex = next ? input.indexOf(next) : undefined;
    return input.substring(startIndex, endIndex);
  }

  const author = book["作者"];
  const publisher = book["出版社"];
  const releaseTime = book["出版年"];
  const isbn = book["ISBN"];
  return {
    bookName,
    author,
    publisher,
    releaseTime,
    isbn,
  };
}

function toTableRow({ bookName, author, publisher, releaseTime, isbn }) {
  return (
    "| " + [bookName, author, publisher, releaseTime, isbn].join(" | ") + " |"
  );
}

function toCsvRow({ bookName, author, publisher, releaseTime, isbn }) {
  return [bookName, author, publisher, releaseTime, isbn].join(",");
}

function appendToFile(filename, text) {
  fs.appendFile(filename, text + "\n", (err) => {
    if (err) {
      console.error(err);
    } else {
      console.log(`写入文件成功：${filename}`);
    }
  });
}

const filename = String.raw`D:\LiuZhaoHui\私人网盘\笔记\Obsidian\工作笔记\PHP\0. 书籍.md`;

const input = `
作者: 凯文·塔特罗 (Kevin Tatroe) / 彼得·麦金太尔 (Peter MacIntyre) / 拉斯马斯·勒多夫 (Rasmus Lerdorf)
出版社: 电子工业出版社
译者: 赵戈戈 / 易国磐 / 张鹏飞
出版年: 2015-3-1
页数: 510
定价: CNY 99.00
装帧: 平装
丛书: O'Reilly动物系列（中译本）
ISBN: 9787121253126
`;

appendToFile(filename, toTableRow(parseDoubanBook("PHP编程", input)));
